const { initOtherData } = require("./task_replyMsg");

const replyComment = {
    taskConfig: {},
    messageData: {},
    replayUserList: [],
    nowReplayIndex: 0,
    saveFileList: 0,
    saveFilePath: [],
    resolveList: [],
    comment_group: {},
    initOtherData() {
        if (replyComment.saveFilePath.length) {
            replyComment.saveFilePath.forEach((item) => {
                files.remove(item)
            })
            replyComment.saveFilePath = []
        }
        replyComment.resolveList = []
    },
    watchValue(key, newVal) {
        switch (key) {
            case 'taskStatus':
                if (newVal) {
                    //当前回复任务已全部完成
                    //销毁保存文件
                    replyComment.initOtherData()
                    console.log('replyComment.replayUserList:' + JSON.stringify(replyComment.replayUserList));
                    Xhs.taskConfig.taskStatus = true
                }
                break;
            case 'errorTask':
                if (newVal) {
                    let params = {
                        taskType: 'reply_comment',
                        taskName: '回复消息',
                        taskData: replyComment.messageData,
                        errorTip: newVal,
                        taskDate: Comman.getDate()
                    }
                    Xhs.errorTask(params)
                    replyComment.taskConfig.taskStatus = true
                }
                break;
            default:
                break;

        }
    },
    init(data) {
        replyComment.initOtherData()
        replyComment.replayUserList = []
        replyComment.messageData = data
        replyComment.taskConfig = Comman.defineReactive(
            { taskStatus: false, errorTask: '' },
            '',
            replyComment.watchValue
        )
    },
    start(data) {
        replyComment.init(data)
        let key = replyComment.messageData.skey
        //处理图片资源文件
        let comment_group = data.setting.comment_group.length ? Comman.getRandomArrayItem(data.setting.comment_group) : {}
        replyComment.comment_group = comment_group
        if (comment_group.image || comment_group.video) {
            replyComment.resolveMiddle(comment_group)
        }
        console.log('回复任务：文件全部下载完成');
        replyComment.toOpenTask()
    },
    resolveMiddle(comment_group) {
        let resource = []
        if (comment_group.image) {
            resource = comment_group.image.split(',')
        }
        if (comment_group.video) {
            resource.push(comment_group.video)
        }
        if (resource.length) {
            myUi.setTopText(Comman.getDate() + ': 回复评论和@任务：' + "资源准备中....")
            let num = 0
            resource.forEach((item, index) => {
                if (!item) {
                    return
                }
                let urlName = item.split('/').slice(-1)[0]
                if (!urlName) {
                    console.log('回复任务：文件解析名称失败：' + item);
                    return
                }
                let filePath = Xhs.resourcePath + new Date().getTime() + '_' + urlName
                let fileStatus = files.createWithDirs(filePath)
                let response = http.get(item);
                if (response.statusCode == 200) {
                    let fileBytes = response.body.bytes();
                    files.writeBytes(filePath, fileBytes);
                    media.scanFile(filePath);
                    replyComment.saveFilePath.push(filePath)
                    num += 1
                    console.log('回复任务：文件下载完成：' + item + ' ---------NO：' + index);
                } else {
                    console.log('回复任务：文件解析名称失败' + response.statusCode);
                }
                sleep(500)
            })
            replyComment.saveFileList = num
        }
        sleep(1000)
    },
    toOpenTask() {
        // 1.打开消息
        let openBtn = btnConfig.home.homeMessageBtn.default()
        if (!openBtn) {
            console.log('回复任务：消息按钮控件获取失败');
            replyComment.taskConfig.errorTask = '消息按钮控件获取失败'
            return
        }
        if (openBtn.bounds) {
            App.clickByBtn(openBtn, 3)
        } else {
            App.click(btnConfig.home.homeMessageBtn.position.x, btnConfig.home.homeMessageBtn.position.y, 3)
        }
        sleep(2000)
        //2.下来刷新数据，更新最新
        gestures([350, [300, 400], [300, 1400]]);
        sleep(2000)
        replyComment.openTask()
    },
    openTask() {
        let num = 0
        let newsBtn = btnConfig.message.messageHomeAttBtn.default()
        let scollNewsList = btnConfig.message.messageHomeScroll.default()
        let messageHomeBtnMenu = btnConfig.message.messageHomeBtnMenu
        if (scollNewsList) {
            // 置顶
            while (!depth(messageHomeBtnMenu.options.depth).id(messageHomeBtnMenu.options.id).exists()) {
                scollNewsList.scrollBackward()
            }
            //未查到有未读，重置后继续查询
            while (!newsBtn && num < 3) {
                gestures([350, [300, 400], [300, 1400]]);
                sleep(3000)
                newsBtn = btnConfig.message.messageHomeAttBtn.default()
                num += 1
                sleep(3000)
            }
            if (!newsBtn && num >= 3) {
                console.log('回复任务：没有新回复消息');
                replyComment.taskConfig.taskStatus = true
                return
            }
            if (newsBtn.bounds) {
                App.clickByBtn(newsBtn, 3)
            } else {
                App.click(btnConfig.message.messageHomeAttBtn.position.x, btnConfig.message.messageHomeAttBtn.position.y, 3)
            }
            replyComment.replayMessage()

        } else {
            console.log('回复任务：消息列表控件获取失败');
            replyComment.taskConfig.errorTask = '消息列表控件获取失败'
            return
        }
    },
    replayMessage() {
        let tip = text('不再提醒').findOne(2000)
        if (tip) {
            console.log('存在提示，点击关闭')
            App.clickByBtn(tip, 3)
        }
        let searchKey = replyComment.messageData.setting.comment_keyword
        let scrollMessageList = btnConfig.message.messageAttScroll.default() //列表区域-自适应滚动
        let messageItems = btnConfig.message.messageAttItem.default() //消息列表项
        let resolveList = replyComment.resolveList//回复列表
        if (scrollMessageList) {
            let bottomDom = btnConfig.message.messageAttScrollbottom.default() //底部控件
            if (!messageItems.empty()) {
                let foreachList = messageItems.slice(0, -1)
                if (bottomDom) {
                    //更新触底标志
                    foreachList = messageItems
                }
                console.log('当前获取消息列表：' + foreachList.length);
                //挨个遍历消息列表，查找关键字
                foreachList.forEach(function (item, index) {
                    let message = item.findOne(id(btnConfig.message.messageAttScrollTitle.options.id))
                    //匹配最新回复
                    if (message) {
                        let info = message.text()
                        console.log('回复消息：', info);
                        if (!info.includes(searchKey) && resolveList.findIndex(item => item == info) == -1) {
                            console.log('关键词未识别，只收集用户信息...');
                            replyComment.nowReplayIndex = index
                            App.randomSleep(2, 5)
                            replyComment.getUserInfo(info, null)
                        }
                        if (info.includes(searchKey) && resolveList.findIndex(item => item == info) == -1) {
                            console.log('满足回复条件，开始发送消息...');
                            let resolceBtns = item.findOne(text('回复'))
                            if (resolceBtns) {
                                replyComment.resolveList.push(info)
                                console.log('识别到回复按钮');
                                //同步正在回复第几条消息-配合点击用户头像-获取用户主页
                                replyComment.nowReplayIndex = index
                                replyComment.resolveMessage(resolceBtns, info);
                            }
                        }
                    }
                    sleep(500)
                });
                if (!bottomDom) {
                    //未触底，继续翻页
                    if (scrollMessageList.scrollForward()) {
                        replyComment.replayMessage()
                    }
                } else {
                    //触底了，任务结束
                    console.log('触底了，任务结束');

                    replyComment.taskConfig.taskStatus = true
                }

            }
        } else {
            console.log('回复任务：报错--无法获取消息列表区域');
            replyMsg.taskConfig.errorTask = '无法获取消息列表区域'
        }
    },
    // 处理回复内容
    resolveMessage(resolceBtns, info) {
        let comment_group = replyComment.comment_group
        //点击开始回复
        App.clickByBtn(resolceBtns, true)
        // 保持内容文本为空
        setText('')
        sleep(2000)
        // 设置回复文本
        let sendBtn = btnConfig.post.infoSendBtn.default() || btnConfig.post.infoSendBtn2.default()
        if (comment_group.content) {
            setText(comment_group.content)
        }
        App.randomSleep(3, 5)
        //设置回复图片资源文件
        if (comment_group.image && replyComment.saveFileList) {
            replyComment.chooseFile(comment_group)
        }
        if (!sendBtn) {
            console.log('回复任务：无法获取发送按钮');
            return
        }
        if (sendBtn.bounds) {
            App.clickByBtn(sendBtn, true)
        } else {
            App.click(btnConfig.post.infoSendBtn.position.x, btnConfig.post.infoSendBtn.position.y, true)
        }
        App.randomSleep(2, 4)
        replyComment.getUserInfo(info, comment_group)
    },
    getUserInfo(info, comment_group) {
        let userImgBtn = btnConfig.message.messageAttItemImg.default()
        if (userImgBtn.length) {
            App.clickByBtn(userImgBtn[replyComment.nowReplayIndex], true)
            let userLocation = btnConfig.user.userPageLocation.default()
            let userNick = btnConfig.user.userPageNick.default()
            let follow = btnConfig.user.userPagefollow.default()
            let fans = btnConfig.user.userPagefans.default()
            let like = btnConfig.user.userPagelike.default()
            let gender = btnConfig.user.userPageGender.default()
            let deal_content = comment_group ? JSON.stringify(comment_group) : ''
            let userId = btnConfig.user.userPageId.default()

            if (userId) {
                let userInfo = {
                    like_num: like ? like.desc().replace('获赞与收藏', '') : 0,
                    fans_num: fans ? fans.desc().replace('粉丝', '') : 0,
                    follow_num: follow ? follow.desc().replace('关注', '') : 0,
                    gender: gender ? gender.desc().replace(',', '') : '',
                    xhsid: userId.text().replace('小红书号：', ''),
                    nickname: userNick ? userNick.text() : '',
                    avatar: "",
                    ip: userLocation ? userLocation.text().replace('IP属地：', '') : '',
                    msg_type: "reply_comment",
                    content: info, deal_content: deal_content
                }
                console.log('userInfo', userInfo);
                replyComment.replayUserList.push(userInfo)
            } else {
                console.log('回复任务：报错--无法获取用户信息');
            }
            sleep(2000)
            back()
            sleep(2000)
        } else {
            console.log('回复任务：报错--无法获取用户头像按钮');
        }
        sleep(2000)
    },
    chooseFile() {
        let filebtn = btnConfig.message.messageAttItemFileBtn.default()
        if (!filebtn) {
            console.log('回复任务：无法获取文件选择按钮');
            App.randomSleep(3, 5)
            return
        }
        if (filebtn.bounds) {
            App.clickByBtn(filebtn, true)
        } else {
            App.click(btnConfig.message.messageAttItemFileBtn.position.x, btnConfig.message.messageAttItemFileBtn.position.y, true)
        }
        // 等待文件选择界面加载完成
        let messageFileMenu = btnConfig.file.messageFileMenu.default()
        if (!messageFileMenu) {
            console.log('回复任务：无法加载文件选择界面');
            return
        }
        // 文件项加载
        let fileItem = btnConfig.file.messageFileItem.default()
        if (!fileItem.length) {
            console.log('回复任务：无法获取文件列表');
            return
        }
        fileItem.forEach(function (file, index) {
            if (index < replyComment.saveFileList) {
                App.clickByBtn(file, 2)
            }
        })
    }
}
module.exports = replyComment